<template>
    <canvas id="canvas"></canvas>
</template>

<script setup lang="ts">
  import {onMounted} from "vue";
  import RenderContext from "@/views/cg/lib/RenderContext.ts";
  import {Model, shape, matrix } from '../lib'
  import gui from "@/views/cg/lib/gui";

  class lotFs extends Model{
    constructor(size) {
      const mesh = shape.d3_f()
      // 调用super 才有 this
      super(null);
      this.size = size;

      for(let i=0;i<10;i++){
        const f= new Model(mesh)
        let unitMatrix = matrix.translate3d(0,0,-size)
        unitMatrix = matrix.multiply4(unitMatrix, matrix.rotateY(2*i*Math.PI/10))
        f.setUnitMatrix(unitMatrix)
        this.addChild(f)
      }
    }

    rotate(angle){
      const aspect = this.gl.canvas.width/this.gl.canvas.height;
      let world = matrix.identity4d()
      world = matrix.multiply4(world, matrix.scale3d(2/210, -2/210, 2/210))
      // 加上旋转矩阵 每个F 都绕着 Y转 加上angle
      world = matrix.multiply4(world, matrix.rotateY(angle))
      world = matrix.multiply4(world, matrix.rotateX(-0.5))
      // 往Z方向移动一点 -10 往里退一下视角
      world = matrix.multiply4(world, matrix.translate3d(-1, -1, -10))
      // 加上透视投影
      world = matrix.multiply4(world, matrix.perspective(
        Math.PI * 0.5,
        aspect,
        1.0,
        1000
      ))
      this.setWorldMatrix06(world)
    }

    setSize(size){
      for (let i=0;i<10;i++){
        let unitMatrix = matrix.translate3d(0,0,-size)
        unitMatrix = matrix.multiply4(unitMatrix, matrix.rotateY(i*Math.Pi/5))
        this.children[i].setUnitMatrix(unitMatrix)
      }
    }
  }

  onMounted(()=>{

    let gl = RenderContext.getGL()
    let m1 = new lotFs(100)
    let m2 = new lotFs(200)
    let m3 = new lotFs(300)

    let angle = 0.0

    let r = 300
    let d = 15


    function draw() {
      m1.rotate(angle)
      m1.setSize(r)
      r+=d
      if(r > 1200){
        d = -d
      }
      if(r < 300 ){
        d = -d
      }
      m2.rotate(angle)
      m3.rotate(angle)

      // 开启深度测试
      gl.enable(gl.DEPTH_TEST);
      gl.depthFunc(gl.LEQUAL)
      // 每次画的时候 画布都设置成最大的深度，深度值越小 权重越高
      gl.clearDepth(1.0)
      gl.viewport(0.0, 0.0, canvas.width, canvas.height)
      // 清空屏幕
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
      angle += 0.01

      m1.draw()
      m2.draw()
      m3.draw()
      requestAnimationFrame(draw)
    }
    draw()
  })
</script>

<style scoped lang="scss">
#canvas{
  width: 100%;
  height: 100%;
  display: block;
}
</style>
